﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using WebApiClientCore.HttpMessageHandlers;

namespace EcoSystem.WebApi
{
    /// <summary>
    /// WebApiClient请求拦截处理程序
    /// 主要用于配置传递token权限
    /// </summary>
    public class HttpApiRequestHandler : AuthorizationHandler
    {
        public IAbpLazyServiceProvider ServiceProvider { get; set; }

        public HttpApiRequestHandler()
        {

        }

        protected override async Task SetAuthorizationAsync(SetReason reason, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var token = await GetTokenAsync();
            request.Headers.Authorization = AuthenticationHeaderValue.Parse(token);
        }

        /// <summary>
        /// 获取当前用户的授权token
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetTokenAsync()
        {
            var accessor = ServiceProvider.LazyGetRequiredService<IHttpContextAccessor>();
            accessor.HttpContext.Request.Headers.TryGetValue("Authorization", out var authorizationHeader);
            return await Task.FromResult(authorizationHeader);
        }
    }
}
